#include "logindialog.h"
#include "ui_logindialog.h"

#include <QLabel>
#include <QTextLine>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QPushButton>

#include <textinput.h>
#include <QIcon>
#include <QComboBox>
#include <QDebug>
#include <QtSql/QSqlDatabase>
#include <QMessageBox>
#include <QtSql/QSqlError>
#include <QStringList>
#include <QTimer>
#include <QThreadPool>
#include <vector>
#include <tcpclient.h>

LoginDialog::LoginDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::LoginDialog)
{
    ui->setupUi(this);
    /* 窗口标题和图片 */
    this->setWindowTitle("智慧医疗管理系统");
    QPixmap pixmap;
    pixmap.load(":/images/TitleIcon.png");
    QIcon icon;
    icon.addPixmap(pixmap);
    this->setWindowIcon(icon);
    /* 窗口标题和图片 */

    ui->labelTitle->setLabelName("智慧医疗系统登录");
    ui->labelTitle->showLabelName();
    createCombox();
    createTextInput();
    createButton();

    m_client = new TcpClient();

    // 连接信号槽
    connect(m_client, &TcpClient::connected,
            [=]()
    {
        qDebug()<<"链接成功"<<endl;
    });
    connect(m_client, &TcpClient::disconnected,
            [=]()
    {
        qDebug()<<"链接断开"<<endl;
    });
    connect(m_client, &TcpClient::dataReceived,
            [=](const QJsonObject& data)
    {
        qDebug()<<"接受信息"<<data["result"].toString()<<endl;
        handleResults(data["result"].toString() == "success"?true:false);
    });
    connect(m_client, &TcpClient::error,
            [=](const QString& errorMessage)
    {
        qDebug()<<"链接错误"<<errorMessage<<endl;
    });
//    connect()
    // 确保在发送数据前已经连接
    if (!m_client->isConnected()) {
        m_client->connectToServer("106.54.213.237", 8080);
    }
}

LoginDialog::~LoginDialog()
{
    delete ui;
}

void LoginDialog::createButton()
{
    buttot_1 = new QPushButton();
    buttot_2 = new QPushButton();

    buttot_1->setText("登录");
    buttot_2->setText("注册");

    buttonLayout = new QHBoxLayout(ui->buttonWidget);
    buttonLayout->addStretch();
    buttonLayout->addWidget(buttot_1);
    buttonLayout->addWidget(buttot_2);
    buttonLayout->addStretch();

    connect(buttot_1,&QPushButton::clicked,
            [=]()
    {
        updateLoginUserInfo();
    });
    connect(buttot_2,&QPushButton::clicked,
            [=]()
    {
        emit this->showToRegisterDialog();
    });
}

void LoginDialog::createTextInput()
{
    ui->textInput_1->setLabelName("用户名");
    ui->textInput_1->setPlaceholderText("请输入用户名");
    ui->textInput_1->setTextInputModel("Normal");
    ui->textInput_1->showTextInput();

    ui->textInput_2->setLabelName("密码");
    ui->textInput_2->setPlaceholderText("请输入密码");
    ui->textInput_2->setTextInputModel("Password");
    ui->textInput_2->showTextInput();
}

void LoginDialog::createCombox()
{
    // 创建 QComboBox 对象
    comboBox = new QComboBox();
    // 添加选项
    comboBox->addItem("患者");
    roleLabel = new QLabel();
    roleLabel->setText("角色选择");
    roleLayout = new QHBoxLayout(ui->role);
    roleLayout->addStretch();
    roleLayout->addWidget(roleLabel);
    roleLayout->addWidget(comboBox);
    roleLayout->addStretch();
}

void LoginDialog::updateLoginUserInfo()
{
    this->role = this->comboBox->currentText();
    this->username = ui->textInput_1->getTextInput();
    this->password = ui->textInput_2->getTextInput();
    if(ui->textInput_1->getTextInput().size() == 0)
    {
        QMessageBox::information(this, "输入内容", "登录失败,请填写正确用户名");
        return;
    }
    if(ui->textInput_2->getTextInput().size() == 0)
    {
        QMessageBox::information(this, "输入内容", "登录失败,请填写正确密码");
        return;
    }
    QJsonObject jsonObj;
    jsonObj["type"] = "登录";
    jsonObj["tms_user"] = username;
    jsonObj["tms_password"] = password;
    jsonObj["tms_gg"] = role;
    QString quires = QString("SELECT * FROM tms WHERE tms_gg = '%1' AND tms_user = '%2' AND tms_password = '%3'").arg(role, username, password);
    jsonObj["sql"] =quires;

    QJsonDocument doc(jsonObj);
    QByteArray data = doc.toJson();
    qDebug() << "Sending data:" << data; // 调试输出
    m_client->sendData(jsonObj);
}

void LoginDialog::handleResults(const bool& results)
{
    // 处理查询结果
    if (!results) {
            // 没有查询到结果
            QMessageBox::information(this, "登录结果", "登录失败,请检查信息是否填写正确");
        } else {
            // 查询到一个结果
            this->accept();
    }
}

void LoginDialog::handleError(const QString& errorMessage)
{
    qDebug() << "Database error:" << errorMessage;
    QMessageBox::information(this, "注册结果", "注册失败,该账号已存在");
}

void LoginDialog::LinkTCP()
{
    if (!m_client->isConnected()) {
        m_client->connectToServer("106.54.213.237", 8080);
    }
}
